package me.chan.netty.rpc.client.handler;

import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.concurrent.Promise;
import lombok.extern.slf4j.Slf4j;
import me.chan.netty.rpc.msg.RpcResponseMessage;

import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
@ChannelHandler.Sharable
public class RpcResponseMessageHandler  extends SimpleChannelInboundHandler<RpcResponseMessage> {


    public static final Map<Integer, Promise> PROMISE_MAP = new ConcurrentHashMap<>();

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, RpcResponseMessage msg) throws Exception {

        log.debug("msg from server:{}", msg);

        // FIXME  why the promise is null?
        Promise promise = PROMISE_MAP.remove(msg.getSequenceId());
        if (Objects.nonNull(promise)) {
            if (Objects.nonNull(msg.getExceptionValue())) {
                promise.setFailure(new Exception(msg.getExceptionValue()));
            } else {
                promise.setSuccess(msg.getReturnValue());
            }
        }

    }

}
